<template>
    <div class="app-container" v-loading="fullscreenLoading">
        <div v-show="!showMenu" id="group">
            <div class="filter-container">
                <el-input v-model="query.name" class="filter-item w-200" size="medium" placeholder="菜单组名称"></el-input>
                <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchList(resetPage = true)" v-permission="'wechat-groups.index'">搜索</el-button>
                <el-button class="filter-item" type="primary" size="medium" @click="addGroup" v-permission="'wechat-groups.store'">新增菜单组</el-button>
            </div>
            <el-table v-loading="loading" :data="groups" border stripe>
                <el-table-column label="#" align="center" width="100px">
                    <template slot-scope="scope" >
                        {{scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column label="菜单组名称" prop="name" align="center"></el-table-column>
                <el-table-column label="菜单组创建时间" prop="created_at" align="center"></el-table-column>
                <el-table-column label="菜单组启用时间" prop="updated_at" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" icon="el-icon-edit" type="danger" v-if="scope.row.is_enable===1" @click="selectGroup(scope.row)" v-permission="'wechat-groups.update'">停用</el-button>
                        <el-button size="mini" icon="el-icon-edit" type="primary" v-if="scope.row.is_enable===0" @click="selectGroup(scope.row)" v-permission="'wechat-groups.update'">启用</el-button>
                        <el-button class="filter-item" type="primary" size="mini" @click="menuInfo(scope.row.id)" v-permission="'wechat-groups.show'">菜单组详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="query.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="query.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>
            <el-dialog
                    width="400px"
                    :visible.sync="dialogVisible2">
                <el-form :model="groupForm" :rules="rules" ref="groupForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="菜单组名称" prop="name">
                        <el-input v-model="groupForm.name"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitGroupForm">保存</el-button>
                    <el-button @click="resetForm('groupForm')">重置</el-button>
                </div>
            </el-dialog>
        </div>
        <div v-show="showMenu" id="menu">
            <div class="filter-container">
                <el-button type="primary" v-permission="'wechat-menus.store'" @click="addMenuBtn">添加主菜单</el-button>
                <el-button type="primary" @click="showMenu=!showMenu">返回</el-button>
            </div>
            <el-card shadow="hover" class="box-card" v-for="menu in menus" :key="menu.id" v-if="menu.sub_id===0">
                <div slot="header" class="clearfix">
                    <div class="card-header-content">
                        <span class="header-content" style="font-size: 22px;font-weight: 300">{{menu.name}}</span>
                        <span class="header-content" style="line-height: 1.7;color: #409EFF" v-show="menu.type">
                            <!--类型：{{menu.type}}-->
                            <span v-show="menu.type === 'click'">点击</span>
                            <span v-show="menu.type === 'view'">链接</span>
                            <span v-show="menu.type === 'media_id'">素材</span>
                            <span v-show="menu.type === 'miniprogram'">小程序</span>
                        </span>
                        <span class="header-content" style="line-height: 1.7;color: #F56C6C" v-show="menu.key">Key：{{menu.key}}</span>
                        <span class="header-content" style="line-height: 1.7;color: #F56C6C" v-show="menu.key">Text：{{menu.text}}</span>
                        <span class="header-content" style="line-height: 1.7;color: #909399" v-show="menu.url">链接：{{menu.url}}</span>
                        <span class="header-content" style="line-height: 1.7;color: #909399" v-show="menu.pagepath">页面路径：{{menu.pagepath}}</span>
                        <span class="header-content" style="line-height: 1.7;color: #909399" v-show="menu.miniprogram_appid">小程序appid：{{menu.miniprogram_appid}}</span>
                        <span class="header-content" style="line-height: 1.7;color: #909399" v-show="menu.media_id">media_id：{{menu.media_id}}</span>
                    </div>
                    <el-button style="float: right;padding: 0" type="text">
                        <el-switch
                                v-permission="'wechat-menus.update'"
                                style="margin-top: 0px; margin-right: 10px"
                                v-model="menu.is_enable"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0" @change="changeBtnStatus(menu)">
                        </el-switch>
                        <el-button type="danger" size="mini" style="margin-right: 10px" round @click="delSubButton(menu.id)" v-permission="'wechat-menus.destroy'">删除</el-button>
                        <div v-show="menu.is_enable" style="float: right">
                            <el-button type="primary" size="mini" round @click="buttonInfos(menu)" v-permission="'wechat-menus.update'">编辑</el-button>
                            <el-button type="primary" size="mini" round @click="addSubBtn(menu.id)" v-permission="'wechat-menus.store'" v-show="menu.sub_btn_count<5">添加子菜单</el-button>
                        </div>
                    </el-button>
                </div>
                <div v-for="sub_menu in menus" :key="sub_menu.id" v-if="sub_menu.sub_id===menu.id" class="text item clearfix">
                    <div class="card-content">
                        <span class="content" style="font-size: 16px">{{sub_menu.name}}</span>
                        <span class="content" style="color: #409EFF" v-show="sub_menu.type">
                            <!--类型：{{sub_menu.type}}-->
                            <span v-show="sub_menu.type === 'click'">点击</span>
                            <span v-show="sub_menu.type === 'view'">链接</span>
                            <span v-show="sub_menu.type === 'media_id'">素材</span>
                            <span v-show="sub_menu.type === 'miniprogram'">小程序</span>
                        </span>
                        <span class="content" style="color: #F56C6C" v-show="sub_menu.key">Key：{{sub_menu.key}}</span>
                        <span class="content" style="color: #F56C6C" v-show="sub_menu.key">Text：{{sub_menu.text}}</span>
                        <span class="content" style="color: #909399" v-show="sub_menu.url">链接：{{sub_menu.url}}</span>
                        <span class="content" style="color: #909399" v-show="sub_menu.pagepath">页面路径：{{sub_menu.pagepath}}</span>
                        <span class="content" style="color: #909399" v-show="sub_menu.miniprogram_appid">小程序appid：{{sub_menu.miniprogram_appid}}</span>
                        <span class="content" style="color: #909399" v-show="sub_menu.media_id">media_id：{{sub_menu.media_id}}</span>
                    </div>
                    <div class="card-content-btn">
                        <el-button style="float: right; padding: 3px" type="primary" icon="el-icon-edit" circle @click="buttonInfos(sub_menu)" v-permission="'wechat-menus.update'"></el-button>
                        <el-button style="float: right; padding: 3px; margin-right: 10px" type="danger" icon="el-icon-delete" circle v-permission="'wechat-menus.destroy'" @click="delSubButton(sub_menu.id)"></el-button>
                    </div>
                </div>
            </el-card>
            <el-dialog
                    width="550px"
                    :visible.sync="dialogVisible">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm" style="padding-right: 70px">
                    <el-form-item label="菜单名称" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="sort" prop="sort">
                        <el-input-number v-model="ruleForm.sort" :min="1" label="sort"></el-input-number>
                    </el-form-item>
                    <div v-if="show">
                        <el-form-item label="类型" prop="type">
                            <el-select v-model="ruleForm.type" placeholder="请选择类型" @change="changeType">
                                <el-option label="click" value="click"></el-option>
                                <el-option label="view" value="view"></el-option>
                                <el-option label="media_id" value="media_id"></el-option>
                                <el-option label="miniprogram" value="miniprogram"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Key" prop="key" v-if="ruleForm.type==='click'">
                            <el-input type="text" v-model="ruleForm.key"></el-input>
                        </el-form-item>
                        <el-form-item label="Text" prop="text" v-if="ruleForm.type==='click'">
                            <el-input type="textarea" v-model="ruleForm.text"></el-input>
                        </el-form-item>
                        <el-form-item label="Url" prop="url" v-if="ruleForm.type==='view' || ruleForm.type==='miniprogram'">
                            <el-input type="text" v-model="ruleForm.url"></el-input>
                        </el-form-item>
                        <el-form-item label="Media_id" prop="media_id" v-if="ruleForm.type==='media_id'">
                            <el-input type="text" v-model="ruleForm.media_id"></el-input>
                        </el-form-item>
                        <el-form-item label="pagePath" prop="pagepath" v-if="ruleForm.type==='miniprogram'">
                            <el-input type="text" v-model="ruleForm.pagepath"></el-input>
                        </el-form-item>
                        <el-form-item label="miniprogramAppID" prop="miniprogram_appid" v-if="ruleForm.type==='miniprogram'">
                            <el-input type="text" v-model="ruleForm.miniprogram_appid"></el-input>
                        </el-form-item>
                    </div>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitForm()">保存</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import { addSubButton, editButton, delButton, wechatGroups, addWechatGroup, updateWechatGroup, groupInfo, applyWechatMenu } from '@/api/wechat'
    export default {
      name: 'menus',
      data() {
        return {
          fullscreenLoading: false,
          loading: true,
          wechatMenu: {
            group_id: ''
          },
          nowGroupId: '',
          showMenu: false,
          groupForm: {
            name: ''
          },
          total: 0,
          query: {
            name: ''
          },
          groups: [],
          show: '',
          type: '',
          menus: [],
          dialogVisible: false,
          dialogVisible2: false,
          ruleForm: {
            id: '',
            name: '',
            sort: '',
            type: '',
            key: '',
            text: '',
            url: '',
            media_id: '',
            pagepath: '',
            is_enable: '',
            sub_id: '',
            miniprogram_appid: ''
          },
          rules: {
            name: [
              { required: true, message: '请输入菜单名称', trigger: 'blur' },
              { min: 2, max: 20, message: '输入的名称长度在2 ~ 20个字符之间' }
            ],
            url: [
              { type: 'url', message: '请输入正确的网址', trigger: ['blur', 'change'] },
              { required: true, message: '请输入菜单链接', trigger: 'blur' }
            ],
            key: [
              { required: true, message: '请输入菜单关键字', trigger: 'blur' }
            ],
            text: [
              { required: true, message: '请输入关键字回复内容', trigger: 'blur' }
            ],
            media_id: [
              { required: true, message: '请输入素材id', trigger: 'blur' }
            ],
            pagepath: [
              { required: true, message: '请输入小程序页面地址', trigger: 'blur' }
            ],
            miniprogram_appid: [
              { required: true, message: '请输入小程序appid', trigger: 'blur' }
            ]
          }
        }
      },
      methods: {
        // 重置表单验证
        resetForm(formName) {
          // 第一次新增数据时为空对象undefined
          if (this.$refs[formName] !== undefined) {
            this.$refs[formName].resetFields()
          }
        },
        // 查询该活动下的菜单信息
        menuInfo(id) {
          this.fullscreenLoading = true
          this.nowGroupId = id
          groupInfo(id).then(res => {
            this.menus = res
            this.showMenu = true
            this.fullscreenLoading = false
          })
        },
        // 启用 停用 活动
        selectGroup(row) {
          this.groupForm = {}
          if (row.is_enable === 0) {
            // 启用
            this.$confirm('此菜单组一经启用，其他菜单组将失效，确定启用?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              updateWechatGroup(this.groupForm, row.id).then(res => {
                // 修改数据库成功之后，将启用的活动下的菜单应用到微信中
                this.wechatMenu.group_id = row.id
                applyWechatMenu(this.wechatMenu).then(res => {
                  if (res.errcode === 0) {
                    this.$message.success('启用成功')
                  } else {
                    this.$message.error(res.errmsg)
                  }
                }).catch((err) => {
                  this.$handleNotFound(err)
                })
                this.fetchList()
              }).catch(err => {
                this.$handleNotFound(err, '活动不存在')
              })
            }).catch(() => {})
          } else {
            // 停用
            this.$confirm('一经停用，公众号菜单栏将置为空，确定停用?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              updateWechatGroup(this.groupForm, row.id).then(res => {
                // 修改数据库成功之后，将启用的活动下的菜单应用到微信中
                this.wechatMenu.group_id = row.id
                applyWechatMenu(this.wechatMenu).then(res => {
                  if (res.errcode === 0) {
                    this.$message.success('停用成功')
                  } else {
                    this.$message.error(res.errmsg)
                  }
                }).catch(err => {
                  this.$handleNotFound(err)
                })
                this.fetchList()
              }).catch(err => {
                this.$handleNotFound(err, '活动不存在')
              })
            }).catch(() => {})
          }
        },
        // 新增菜单组
        addGroup() {
          this.groupForm = {}
          this.dialogVisible2 = true
        },
        // 新增菜单组的表单提交
        submitGroupForm() {
          this.$refs['groupForm'].validate((valid) => {
            if (valid) {
              this.loading = true
              addWechatGroup(this.groupForm).then(res => {
                this.$message.success('添加成功')
                this.fetchList()
                this.dialogVisible2 = false
              }).catch(err => {
                this.$handleNotFound(err)
              })
            } else {
              // 未通过验证
            }
          })
        },
        handleSizeChange(size) {
          this.query.size = size
          this.fetchList()
        },
        handleCurrentChange(page) {
          this.query.page = page
          this.fetchList()
        },
        // 活动列表
        fetchList(resetPage = false) {
          this.loading = true
          if (resetPage) {
            this.query.page = 1
          }
          wechatGroups(this.query).then(res => {
            this.groups = res.data
            this.total = res.meta.total
            this.loading = false
          })
        },
        changeType() {
          this.ruleForm.key = ''
          this.ruleForm.url = ''
          if (this.$refs['ruleForm'] !== undefined) {
            this.$refs['ruleForm'].clearValidate()
          }
        },
        buttonInfos(row) {
          if (row.sub_btn_count === 0) {
            this.show = true
          } else {
            this.show = false
          }
          this.type = 'edit'
          Object.existAssign(this.ruleForm, row)
          this.ruleForm.group_id = this.nowGroupId
          this.dialogVisible = true
        },
        // 添加子菜单
        addSubBtn(id) {
          this.show = true
          this.type = 'add'
          this.resetForm('ruleForm')
          Object.assign(this.ruleForm, this.$options.data().ruleForm)
          this.ruleForm.sub_id = id
          this.ruleForm.group_id = this.nowGroupId
          this.dialogVisible = true
        },
        // 添加主菜单
        addMenuBtn() {
          this.show = true
          this.type = 'add'
          this.resetForm('ruleForm')
          Object.assign(this.ruleForm, this.$options.data().ruleForm)
          this.ruleForm.sub_id = 0
          this.ruleForm.group_id = this.nowGroupId
          this.dialogVisible = true
        },
        // 启用 停用菜单
        changeBtnStatus(row) {
          this.ruleForm = row
          this.ruleForm.group_id = this.nowGroupId
          editButton(this.ruleForm, this.ruleForm.id).then(res => {
            if (res.result === 'failed') {
              this.$message.error(res.msg)
            } else {
              this.$message.success('菜单状态更新成功!')
            }
            this.menuInfo(this.nowGroupId)
          }).catch(err => {
            this.$handleNotFound(err, '该菜单不存在')
          })
        },
        // 菜单表单提交
        submitForm() {
          this.$refs['ruleForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              if (this.type === 'add') {
                // Todo 给顶层菜单添加子菜单并且添加成功之后，要去除顶层菜单多余的属性
                addSubButton(this.ruleForm).then(res => {
                  this.$message.success('添加成功!')
                  this.dialogVisible = false
                  this.menuInfo(this.nowGroupId)
                }).catch(err => {
                  this.$handleNotFound(err)
                })
              }
              if (this.type === 'edit') {
                // 判断顶层菜单是否可以编辑其他选项
                if (!this.show) {
                  this.ruleForm.type = ''
                  this.ruleForm.key = ''
                  this.ruleForm.text = ''
                  this.ruleForm.url = ''
                  this.ruleForm.media_id = ''
                  this.ruleForm.pagepath = ''
                  this.ruleForm.miniprogram_appid = ''
                  console.log('已有子菜单的顶层菜单只能编辑菜单名称')
                }
                editButton(this.ruleForm, this.ruleForm.id).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('菜单编辑成功!')
                    this.dialogVisible = false
                  }
                  this.menuInfo(this.nowGroupId)
                }).catch(err => {
                  this.$handleNotFound(err, '该菜单不存在')
                })
              }
            } else {
              // 未通过校验
            }
          })
        },
        // 删除菜单
        delSubButton(id) {
          this.$confirm('确定删除该菜单?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delButton(id).then(res => {
              this.$message.success('删除成功!')
              this.menuInfo(this.nowGroupId)
            }).catch(err => {
              this.$handleNotFound(err, '该菜单不存在')
            })
          }).catch(() => {})
        }
      },
      created() {
        this.fetchList()
      }
    }
</script>

<style scoped>
    .text {
        font-size: 14px;
    }

    .item {
        margin-bottom: 12px;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }

    .clearfix:after {
        clear: both
    }

    .box-card {
        width: 32%;
        height: 270px;
        margin-right: 10px;
        margin-bottom: 10px;
        float: left;
        font-weight: 200
    }

    .header-content {
        margin-right: 10px;
    }

    .card-header-content {
        word-wrap: break-word;
        word-break: break-all;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: block;
        float: left;
        margin-right: 10px;
        font-size: 16px;
        width: 400px;
    }

    .card-content {
        word-wrap: break-word;
        word-break: break-all;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: block;
        float: left;
        margin-right: 10px;
        font-size: 16px;
        width: 500px;
    }

    .card-content-btn {
        display: block;
        float: right;
    }

    .content {
        margin-right: 10px;
    }
</style>
